package org.hotcore;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * Hello world!
 *
 */
public class App 
{
    static Object object = new Object();


    public static void main( String[] args ) throws Exception {
        //Server

        ServerSocketChannel server = ServerSocketChannel.open();
        ServerSocket socket = server.socket();//获得socket
//        socket.setReuseAddress(false);
        server.configureBlocking(false);
        InetSocketAddress address = new InetSocketAddress(8881);
        socket.bind(address);
        Selector sel= Selector.open();
        server.register(sel, SelectionKey.OP_ACCEPT);//注测ACCEPT

        ServerHandler serverHandler = new ServerHandler();
        try{
            while (true) {
                if (sel.select() > 0) {
                    Set<SelectionKey> keys = sel.selectedKeys();
                    Iterator<SelectionKey> iterator = keys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        if (key.isAcceptable()) {
                            serverHandler.handleAccept(key);
                        }
                        if (key.isReadable()) {
                            serverHandler.handleRead(key);
                        }
                        iterator.remove();
                    }
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        System.out.println( "Hello World!" );
    }
}
